<script setup>

import {ref} from "vue";
import axios from "axios";
import webConfig from "@/GlobalParas.js";
import {DownOutlined, HomeOutlined, UserOutlined} from "@ant-design/icons-vue";
import {decrypt} from "@/util/StringOper.js";

let selectedKeys = ref([]);
let treeData = ref([]);

let userDeptId = decrypt(localStorage.getItem("deptId"));

let depts = []
let deptUrl = webConfig.postUrl + '/dept/getAllDepts';

axios.post(deptUrl).then((res) => {
  depts = res.data;//获取所有部门
  getDeptNodes(depts, null, userDeptId)
  // console.log(treeData.value);
})

function getDeptNodes(depts, currentDept, parentId) {
  // console.log(parentId)
  let subDepts;
  if (currentDept === null) {
    subDepts = depts.filter((item) => {
      return item.tableKey === parentId;
    })
  } else {
    subDepts = depts.filter((item) => {
      return item.parentDeptId === parentId;
    })
  }

  subDepts.sort((a, b) => a.sort - b.sort);//按照部门排序顺序显示
  // console.log(subDepts);


  subDepts.forEach((item) => {
    let treeNode = {};
    treeNode.title = item.deptName;
    treeNode.key = item.tableKey;
    treeNode.nodeType = "dept";
    treeNode.children = [];

    if (currentDept === null) {
      treeData.value.push(treeNode);
    } else {
      currentDept.children.push(treeNode)
    }
    getDeptNodes(depts, treeNode, treeNode.key);
  })
}


let emit = defineEmits(["treeNodeClick"])
function onNodeSelect(selectedKeys, e) {
  // console.log(selectedKeys);
  // console.log(e);
  emit("treeNodeClick", e.node)
}
</script>

<template>
  <a-tree
      v-if="treeData.length"
      v-model:selectedKeys="selectedKeys"
      :tree-data="treeData"
      show-icon
      @select="onNodeSelect"
      defaultExpandAll
  >
    <template #switcherIcon="{ switcherCls }">
      <down-outlined :class="switcherCls"/>
    </template>
    <template #icon="{ nodeType }">
      <HomeOutlined/>
    </template>
  </a-tree>
</template>

<style scoped>

</style>